package com.lyn.tencent_health_code.controller;

import com.alibaba.fastjson.JSONObject;
import com.lyn.tencent_health_code.annotation.Login;
import com.lyn.tencent_health_code.config.AdminConfig;
import com.lyn.tencent_health_code.database.User;
import com.lyn.tencent_health_code.entity.ChangePassword;
import com.lyn.tencent_health_code.entity.LoginUser;
import com.lyn.tencent_health_code.entity.RegisteredUser;
import com.lyn.tencent_health_code.entity.RequestResult;
import com.lyn.tencent_health_code.service.EncrypDESService;
import com.lyn.tencent_health_code.service.UserService;
import com.lyn.tencent_health_code.utils.RedisUtil;
import com.lyn.tencent_health_code.utils.TextUtils;
import com.lyn.tencent_health_code.utils.TokenUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
/**
 * @author almost
 */
@Api("用户")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private EncrypDESService encrypDESService;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping(value = "/login")
    public RequestResult login(@RequestBody LoginUser loginUser, HttpServletResponse response) {
        RequestResult result = new RequestResult();
        User user = userService.findByName(loginUser.getUserName());
        if (user == null) {
            result.setMessage("用户名不存在");
            return result;
        }
        String encrypt = encrypDESService.encrypt(loginUser.getUserPassword());
        if (!user.getUserPassword().equals(encrypt)) {
            result.setMessage("密码错误");
            return result;
        }
        loginUser.setUserPassword(encrypt);
        String token = TokenUtils.createToken(encrypDESService, loginUser);
        boolean set = redisUtil.set(token, token, TokenUtils.EXPIRE_DATE);
        if (set) {
            TokenUtils.setToken(token, response);
            JSONObject tokenJson = new JSONObject();
            tokenJson.put(TokenUtils.TOKEN_NAME, token);
            result.setData(tokenJson);
            result.setCode(1);
            result.setMessage("登录成功");
        } else {
            result.setMessage("登录失败");
        }
        return result;
    }

    @Login
    @GetMapping(value = "/generateInvitationCode")
    public RequestResult generateInvitationCode(HttpServletRequest request) {
        RequestResult result = new RequestResult();
        String token = TokenUtils.getToken(request);
        if (TextUtils.isEmpty(token)) {
            result.setMessage("获取邀请码失败");
            return result;
        }
        try {
            LoginUser loginUser = TokenUtils.getLoginUser(encrypDESService, token);
            if (loginUser == null) {
                result.setMessage("获取邀请码失败");
                return result;
            }
            User user = userService.findByName(loginUser.getUserName());
            if (user == null) {
                result.setMessage("获取邀请码失败");
                return result;
            }
            if (user.getType() == AdminConfig.GENERAL_USER) {
                result.setMessage("您没有权限获取邀请码");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String invitationCode = UUID.randomUUID().toString().replaceAll("-", "");
        boolean set = redisUtil.set(invitationCode, invitationCode, 60 * 60 * 24);
        if (set) {
            result.setCode(1);
            result.setData(invitationCode);
        } else {
            result.setMessage("获取邀请码失败");
        }
        return result;
    }



    @PostMapping(value = "/registered")
    public RequestResult registered(@RequestBody RegisteredUser registeredUser) {
        RequestResult result = new RequestResult();
        if (TextUtils.isEmpty(registeredUser.getInvitationCode())) {
            result.setCode(0);
            result.setMessage("邀请码不能为空");
            return result;
        }
        Object o = redisUtil.get(registeredUser.getInvitationCode());
        String invitationCode = null;
        if (o instanceof String) {
            invitationCode = (String) o;
        }
        if (TextUtils.isEmpty(invitationCode)) {
            result.setCode(0);
            result.setMessage("邀请码错误");
            return result;
        }
        if (registeredUser == null || TextUtils.isEmpty(registeredUser.getUserName())) {
            result.setCode(0);
            result.setMessage("用户名不能为空");
            return result;
        }

        if (TextUtils.isEmpty(registeredUser.getUserPassword()) && registeredUser.getUserPassword().length() < 6) {
            result.setCode(0);
            result.setMessage("密码不能少于6位");
            return result;
        }
        if (!registeredUser.getUserPassword().equals(registeredUser.getConfirmPassword())) {
            result.setCode(0);
            result.setMessage("密码和确认密码不一致");
            return result;
        }
        boolean byNameExist = userService.findByNameExist(encrypDESService.encrypt(registeredUser.getUserName()));
        if (byNameExist) {
            result.setCode(0);
            result.setMessage("该用户已经存在");
            return result;
        }
        User user = new User();
        user.setId(UUID.randomUUID().toString());
        user.setUserName(registeredUser.getUserName());
        user.setUserPassword(encrypDESService.encrypt(registeredUser.getConfirmPassword()));
        user.setTime(System.currentTimeMillis());
        user.setType(AdminConfig.GENERAL_USER);
        User save = userService.save(user);
        if (save == null) {
            result.setMessage("注册失败");
            return result;
        }
        redisUtil.del(invitationCode);
        result.setCode(1);
        result.setMessage("注册成功");
        return result;
    }


    @Login
    @PostMapping(value = "/changePassword")
    public RequestResult changePassword(@RequestBody ChangePassword changePassword, HttpServletRequest request,HttpServletResponse response) {
        RequestResult result = new RequestResult();
        try {
            String token = TokenUtils.getToken(request);
            if (TextUtils.isEmpty(token)) {
                result.setMessage("请登录");
                return result;
            }
            LoginUser loginUser = TokenUtils.getLoginUser(encrypDESService, token);
            if (loginUser == null) {
                result.setMessage("请登录");
                return result;
            }
            String oldPassword=encrypDESService.encrypt(changePassword.getOldPassword());
            if (!oldPassword.equals(loginUser.getUserPassword())){
                result.setMessage("旧密码错误");
                return result;
            }
            if (TextUtils.isEmpty(changePassword.getNewPassword())){
                result.setMessage("新密码不能为空");
                return result;
            }
            if (oldPassword.equals(encrypDESService.encrypt(changePassword.getNewPassword()))){
                result.setMessage("新密码和旧密码不能一致");
                return result;
            }
            if (!changePassword.getNewPassword().equals(changePassword.getConfirmTheNewPassword())){
                result.setMessage("新密码和确认密码不一致");
                return result;
            }
            User user = userService.findByName(loginUser.getUserName());
            if (user==null){
                result.setMessage("请登录");
                return result;
            }
            user.setUserPassword(encrypDESService.encrypt(changePassword.getConfirmTheNewPassword()));
            User update = userService.update(user);
            if (update==null){
                result.setMessage("修改失败");
                return result;
            }
            TokenUtils.deleteToken(redisUtil,request,response);
            result.setCode(1);
            result.setMessage("修改密码成功,请重新登录");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
        }
        return result;
    }


    @Login
    @GetMapping(value = "/logout")
    public RequestResult logout(HttpServletRequest request, HttpServletResponse response) {
        RequestResult result = new RequestResult();
        TokenUtils.deleteToken(redisUtil, request, response);
        result.setCode(1);
        result.setMessage("注销成功");
        return result;
    }
}
